package org.baicaix.io {
	import org.baicaix.utils.HashMap;

	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundMixer;
	import flash.media.SoundTransform;
	import flash.utils.getDefinitionByName;

	/**
	 * @author ghdu
	 */
	public class SoundManager {

		private static var channelID : uint;
		private static var allChannel : HashMap = new HashMap();
		private static var _volume : Number = 1;

		public static function playSound(s : Sound,startTime : Number = 0,loops : int = 0,sndTransform : SoundTransform = null) : void {
			addChannel(s.play(startTime, loops, sndTransform));
		}

		public static function playSoundWithLink(soundLink : String,startTime : Number = 0,loops : int = 0,sndTransform : SoundTransform = null) : void {
			var s : Sound = new (getDefinitionByName(soundLink) as Class)();
			addChannel(s.play(startTime, loops, sndTransform));
		}

		public static function addChannel(channel : SoundChannel) : uint {
			allChannel.put(channelID, channel);
			setVolume(channelID, _volume);
			return channelID++;
		}

		public static function removeChannel(id : uint) : void {
			allChannel.remove(id);
		}

		public static function stopSound(id : uint) : void {
			var channel : SoundChannel = allChannel.get(id) as SoundChannel;
			channel.stop();
			allChannel.remove(id);
		}

		public static function stopAllSounds() : void {
			var channelArr : Array = allChannel.values();
			var len : uint = channelArr.length;
			for(var i : uint;i < len;i++) {
				SoundChannel(channelArr[i]).stop();
			}
			allChannel.clear();
			
			SoundMixer.stopAll();
		}

		public static function setVolume(id : uint,val : Number) : void {
			var channel : SoundChannel = allChannel.get(id) as SoundChannel;
			var transform : SoundTransform = channel.soundTransform;
			transform.volume = Math.min(1, Math.max(0, val));
			channel.soundTransform = transform;
		}

		public static function setAllVolume(val : Number) : void {
			var channelArr : Array = allChannel.values();
			var len : uint = channelArr.length;
			var transform : SoundTransform;
			for(var i : uint;i < len;i++) {
				transform = SoundChannel(channelArr[i]).soundTransform;
				transform.volume = Math.min(1, Math.max(0, val));
				SoundChannel(channelArr[i]).soundTransform = transform;
			}
			_volume = val;
			
			transform = SoundMixer.soundTransform;
			transform.volume = Math.min(1, Math.max(0, val));
			SoundMixer.soundTransform = transform;
		}

		public static function getAllVolume() : Number {
			return _volume;
		}
	}
}
